package org.jeecg.access.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.access.entity.AccountData;
import org.jeecg.access.entity.WorkData;
import org.jeecg.access.service.UnifiedPlatformService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @description: todo
 * @author: taogang
 * @date: 2025/7/30 8:48
 */
@Slf4j
public abstract class AbstractCountDataService implements UnifiedPlatformService {
    protected abstract List<AccountData> queryAccountData();
    protected abstract List<WorkData> queryWorksData();

    @Override
    public List<AccountData> getPlatformDetailData() {
        List<AccountData> accounts = safeQuery(this::queryAccountData);
        List<WorkData> works = safeQuery(this::queryWorksData);

        // 如果两者都不为空，进行数据关联
        if (!accounts.isEmpty() && !works.isEmpty()) {
            associateWorks(accounts, works);
        }

        return accounts;
    }

    // 安全的查询方法
    private <T> List<T> safeQuery(Supplier<List<T>> query) {
        try {
            List<T> result = query.get();
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("查询失败", e);
            return new ArrayList<>();
        }
    }

    // 关联作品数据
    private void associateWorks(List<AccountData> accounts, List<WorkData> works) {
        // 创建账户ID到账户对象的映射
        Map<String, AccountData> accountMap = new HashMap<>();
        for (AccountData account : accounts) {
            if (account != null && account.getId() != null) {
                account.setTotalDataList(new ArrayList<>());
                accountMap.put(account.getId(), account);
            }
        }

        // 遍历作品列表，关联到对应的账户
        for (WorkData work : works) {
            if (work != null && work.getUserId() != null) {
                AccountData account = accountMap.get(work.getUserId());
                if (account != null) {
                    account.getTotalDataList().add(work);
                }
            }
        }
    }

}
